package com.ysu.shop.client;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysu.shop.exception.MyException;
import com.ysu.shop.pojo.*;
import com.ysu.shop.service.*;
import com.ysu.shop.utils.InitUtil;
import com.ysu.shop.utils.JwtUtil;
import com.ysu.shop.utils.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Transactional(noRollbackFor={MyException.class},rollbackFor = Exception.class)
public class OrderController {
    @Resource
    private IOrderdetailService orderDetailService;

    @Resource
    private IOrdersService ordersService;

    @Resource
    private IGoodsService goodsService;

    @Resource
    private IShoppingcartService cartService;

    @Resource
    private IAddressService addressService;

    @Resource
    private IPayService payService;

    @PostMapping()
    public Result addOrder(@RequestBody Map<String,Object> param , HttpServletRequest request){
        int userId = JwtUtil.getUserId(request);
        String orderNo = System.currentTimeMillis()+""+userId;
        Orders orders = new Orders();
        orders.setPayment(new BigDecimal(param.get("payment").toString()));
        orders.setOrderNo(orderNo);
        orders.setUserId(userId);
        if (!ordersService.save(orders)){
            return Result.getFailResult("订单创建失败");
        }
        QueryWrapper<Shoppingcart> wrapper = new QueryWrapper<>();
        String ids=param.get("ids").toString();
        wrapper.inSql("id",ids);
        List<Shoppingcart> goods = cartService.list(wrapper);
        List<Orderdetail> orderList = new ArrayList<>();
        for (Shoppingcart i:goods){
            Orderdetail order = new Orderdetail();
            order.setOrderNo(orderNo);
            order.setUserId(userId);
            order.addOrderItem(i);
            orderList.add(order);
        }
        orderDetailService.saveBatch(orderList);
        cartService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.getSuccessResult(orderNo);
    }

    /**
     * 通过订单号 返回 购买的商品
     * @return
     */
    @GetMapping("/detail/{id}")
    @Transactional(readOnly = true)
    public Result getOrderList(@PathVariable String id){
        QueryWrapper<Orderdetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",id);
        return Result.getSuccessResult(orderDetailService.list(wrapper));
    }

    /**
     * 通过订单号 返回订单信息
     * @return
     */
    @GetMapping("/{id}")
    @Transactional(readOnly = true)
    public Result getOrderById(@PathVariable String id){
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",id).eq("status",0);
        return Result.getSuccessResult(ordersService.getOne(wrapper));
    }

    /**
     * 付款成功
     */
    @PutMapping("/payment/{id}")
    public Result payment(@PathVariable String id,@RequestBody Map<String,Object> param){
        Object addrId = param.get("addrId");
        if (StringUtils.isEmpty(addrId)){
            return Result.getFailResult("","未选择收货地址");
        }
        int addressId = Integer.valueOf(addrId.toString());
        if (ordersService.payment(id,addressId)>0){
            Pay pay = new Pay();
            pay.setOrderNo(id);
            pay.addPay(addressService.getById(addressId));
            pay.setPayment(new BigDecimal(param.get("payment").toString()));
            if (payService.save(pay)){
                return Result.getSuccessResult(pay.getPlatformNumber());
            }
        }
        return Result.getFailResult("","付款失败");

    }

    /**
     * 取消订单
     */
    @PutMapping("/cancel/{id}")
    public Result cancel(@PathVariable String id){
        if (ordersService.cancel(id)>0){
            return Result.getSuccessResult("取消订单成功");
        }
        return Result.getFailResult("","取消订单失败");
    }

    /**
     * 发货
     */
    @PutMapping("/admin/send/{id}")
    public Result send(@PathVariable int id){
        if (orderDetailService.send(id)>0){
            return Result.getSuccessResult("发货成功");
        }
        return Result.getFailResult("","发货失败");
    }

    /**
     * 收货
     */
    @PutMapping("/receive/{id}")
    public Result receive(@PathVariable int id){
        if (orderDetailService.receive(id)>0){
            return Result.getSuccessResult("收货成功");
        }
        return Result.getFailResult("","收货失败");
    }

    /**
     * 获取支付信息
     */
    @GetMapping("/pay/{id}")
    @Transactional(readOnly = true)
    public Result getPay(@PathVariable String id){
        QueryWrapper<Pay> wrapper = new QueryWrapper<>();
        wrapper.eq("platform_number",id);
        return Result.getSuccessResult(payService.getOne(wrapper));
    }

    /**
     * 获取所有的订单信息
     */
    @GetMapping("/admin")
    public Result getOrderItems(@RequestParam Map<String,Object> param,HttpServletRequest request){
        return Result.getSuccessResult(orderDetailService.getOrderItem(param,JwtUtil.getUserId(request)));
    }

    /**
     * 获取用户购买的所有商品
     */
    @GetMapping("/goods")
    public Result getAllOrder(HttpServletRequest request){
        QueryWrapper<Orderdetail> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",JwtUtil.getUserId(request));
        wrapper.gt("status",1);
        return Result.getSuccessResult(orderDetailService.list(wrapper));
    }

}
